package org.ftpscan;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * Class for saving information from FTP scanning in XML format.
 *
 * @author Nikolai Holub (nikolai.holub at gmail.com)
 */
public class XMLDocument {
    private static final DateFormat DATE_FORMAT =
        new SimpleDateFormat("yyyy-MM-dd HH:mm");

    private Logger log = Logger.getLogger(getClass().getPackage().getName());

    private Document document;
    private Element root;

    /**
     * Constructs XMLDocument.
     *
     * @param host host
     * @param dir scan directory
     * @param date scan date
     */
    public XMLDocument(String host, String dir, Date date) {
        document = DocumentHelper.createDocument();

        root = document.addElement("files");

        root.addAttribute("host", host);
        root.addAttribute("scan_dir", dir);
        root.addAttribute("scan_date", DATE_FORMAT.format(date));
    }

    /**
     * Returns XML document.
     *
     * @return XML document
     */
    public Document getDocument() {
        return document;
    }

    /**
     * Adds information about file to the XML document.
     *
     * @param dir file directory
     * @param file FTPFile
     */
    public void addFile(String dir, FTPFile file) {
        Element entry = root.addElement("file");

        entry.addAttribute("name", file.getName());
        entry.addAttribute("dir", dir);
        entry.addAttribute("size", String.valueOf(file.getSize()));

        entry.addAttribute("date",
            DATE_FORMAT.format(file.getTimestamp().getTime()));
    }

    /**
     * Saves XML document to the specified file.
     *
     * @param fileName file name
     * @throws IOException if IO exception occurs
     */
    public void save(String fileName) throws IOException {
        log.info("saving data to " + fileName + "...");

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        FileOutputStream out = new FileOutputStream(fileName);
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        out.close();

        log.info(fileName + " saved");
    }
}
